//
//  ComposeViewController.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/24.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    // 照片选择控制器属性
    private lazy var picturePickerController = PicturePickerController()
    
    /// MARK: - 监听方法
    @objc private func close() {
        
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendStatus() {
       // print("发布微博")
        // 1. 获取文本内容
        let text = textView.emoticonText
        // 2. 发布微博
        let image = picturePickerController.pictures.last
        NetworkTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
            if error != nil {
            //print("出错了")
            SVProgressHUD.showInfoWithStatus("您的网速不给力")
                return
            }
            
            //print(result)
            SVProgressHUD.showInfoWithStatus("发布成功")
            // 关闭控制器
            delay(2.5) {
            
                self.close()
            }
        }
        
    }
    /// MARK: - 选择照片
    @objc private func selectPicture() {
        print("选择照片 \(picturePickerController.view.frame)")
        
        // 退掉键盘
        textView.resignFirstResponder()
        
        // 0. 判断如果已经更新了约束，不再执行后续代码
        if picturePickerController.view.frame.height > 0 {
            return
        }
        
        // 1. 修改照片选择控制器视图的约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        // 2. 修改文本视图的约束 - 重建约束 - 会将之前`textView`的所有的约束删除
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        // 3. 动画更新约束
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    /// MARK: - 选择表情
    @objc private func selectEmoticon() {
        print("选择表情\(textView.inputView)")
        
        // 1. 退掉键盘
        textView.resignFirstResponder()
        
        // 2. 设置键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        // 3. 重新激活键盘
        textView.becomeFirstResponder()
    }
    
    /// MARK: - 键盘变化的处理
    @objc private func keyboardChanged(n: NSNotification) {
    
        //print(n)
        
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        // 动画曲线
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset = -view.bounds.height + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
         UIView.animateWithDuration(duration) { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
        // 调试动画时长
        //let anim = toolBar.layer.animationForKey("position")
        //print("动画时长\(anim)")
    }
    
    /// MARK: - 键盘处理 
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardChanged:",
            name: UIKeyboardWillChangeFrameNotification,
            object: nil)
    }
    
    deinit {
    // 注销键盘
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    override func loadView() {
        view = UIView()
        
        setupUI()
    }
    
    /// MARK: - 键盘处理(view 将要出现的时候 把键盘叫出来)
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if picturePickerController.view.bounds.height == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    
    /// 懒加载工具栏
    private lazy var toolBar = UIToolbar()
    
    /// 懒加载视图
    private lazy var textView: UITextView = {
        
        let tv = UITextView()
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        // 容许垂直滚动
        tv.alwaysBounceVertical = true
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.delegate = self
        return tv
        
        
        }()
    
    
    /// 占位标签
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事......",
        fontSize: 18,
        color: UIColor.lightGrayColor())
    
    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }

}

/// MARK: - 设置界面
extension ComposeViewController {

    /// MARK: - 设置界面
     func setupUI() {
        
        // 取消滚动视图的自动缩紧（重要）
        automaticallyAdjustsScrollViewInsets = false
        
        // 设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        // 设置控件
        prepareNavigation()
        prepatrToolBar()
        prepareTextView()
        preparePicturePicker()
    }
    
    /// MARK: - 准备照片视图
    private func preparePicturePicker() {
        
        // 0. 添加子控制器
        addChildViewController(picturePickerController)
        
        // 1. 添加视图
        view.insertSubview(picturePickerController.view, belowSubview: toolBar)
        // 2. 自动布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
    }
    
    /// MARK: - 准备文本视图
    private func prepareTextView(){
    
        view.addSubview(textView)
        
        // 设置自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
       // textView.text = "分享新鲜事......"
        
        // 添加占位标签
        textView.addSubview(placeHolderLabel)
        // 占为标签的自动布局
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    /// MARK: - 准备导航栏
    private func prepareNavigation() {
    
        // 1. 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendStatus")
       
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 2. 标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        // 3. 添加自控件
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        // 自动布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
        navigationItem.titleView = titleView
    }
    
    /// MARK: - 添加工具按钮
    func prepatrToolBar() {
        view.addSubview(toolBar)
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 添加工具栏按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName":"selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
        
            let button = UIButton(imageName: dict["imageName"]!, backImageName: "")
            
            // 判断 actionName
            if let actionName = dict["actionName"] {
                button.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            items.append(UIBarButtonItem(customView: button))
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        toolBar.items = items
    }
    
}

// MARK: - UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}
